package com.yufubao.service.service.management.check.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yufubao.framework.exception.BaseException;
import com.yufubao.framework.result.PageUtils;
import com.yufubao.framework.result.ResponseResult;
import com.yufubao.framework.util.CopyBean;
import com.yufubao.framework.util.MyCollUtil;
import com.yufubao.model.dto.management.check.MerchantApplicationDto;
import com.yufubao.model.pojo.applet.authorization.UserEntity;
import com.yufubao.model.pojo.applet.elasticsearch.SupplierEsModel;
import com.yufubao.model.pojo.applet.product.SupplierApplyFailLogEntity;
import com.yufubao.model.pojo.applet.product.SupplierInfoEntity;
import com.yufubao.model.pojo.common.SupplierFailCauseLogEntity;
import com.yufubao.model.vo.management.check.SearchAllStatusInfoVo;
import com.yufubao.service.service.applet.authorization.UserService;
import com.yufubao.service.service.applet.product.SpuInfoService;
import com.yufubao.service.service.applet.product.SupplierApplyFailLogService;
import com.yufubao.service.service.applet.product.SupplierInfoService;
import com.yufubao.service.service.common.SupplierFailCauseLogService;
import com.yufubao.service.service.common.util.ServiceUtil;
import com.yufubao.service.service.management.check.CheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.yufubao.framework.constant.SupplierInfoConstant.*;
import static com.yufubao.framework.constant.UserTypeConstant.USER_STATE_YES;
import static com.yufubao.framework.constant.UserTypeConstant.USER_TYPE_SHANG;
import static com.yufubao.framework.enums.CommonExceptionEnum.DATE_NOT_DATA;
import static com.yufubao.framework.enums.CommonExceptionEnum.NOT_FOUND_HYBSH;
import static com.yufubao.framework.util.MapParamsUtil.getStatus;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/9/5 23:07
 */
@Service("checkService")
public class CheckServiceImpl implements CheckService {


    @Autowired
    private UserService userService;

    @Autowired
    private SupplierInfoService supplierInfoService;

    @Autowired
    private SupplierApplyFailLogService supplierApplyFailLogService;


    @Autowired
    private SupplierFailCauseLogService supplierFailCauseLogService;

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private ServiceUtil serviceUtil;

    /**
     * @param dto
     * @return com.yufubao.framework.result.ResponseResult
     * @description 用户申请商户成功
     * @author zhangyiheng
     * @date 2024/8/29 23:31
     */
    @Override
    @Transactional
    public ResponseResult merchantApplicationSuccess(MerchantApplicationDto dto) {

        //删除审核失败日志
        if (StrUtil.isAllNotBlank(dto.getLegalPerson(), dto.getStoreName(), dto.getIdNumber(), dto.getAddress())) {
            supplierApplyFailLogService.remove(Wrappers.<SupplierApplyFailLogEntity>lambdaQuery()
                    .eq(SupplierApplyFailLogEntity::getLegalPerson, dto.getLegalPerson())
                    .eq(SupplierApplyFailLogEntity::getStoreName, dto.getStoreName())
                    .eq(SupplierApplyFailLogEntity::getIdNumber, dto.getIdNumber())
                    .eq(SupplierApplyFailLogEntity::getAddress, dto.getAddress()));
            //TODO 日志表
        }

        //修改审核状态
        supplierInfoService.update(Wrappers.<SupplierInfoEntity>lambdaUpdate()
                .set(SupplierInfoEntity::getStatus, USER_STATE_YES)
                .set(SupplierInfoEntity::getAuditor, StpUtil.getLoginIdAsLong())
                .eq(SupplierInfoEntity::getSupplierInfoId, dto.getSupplierInfoId()));

        SupplierInfoEntity supplierInfo = supplierInfoService.getById(dto.getSupplierInfoId());

        //修改小程序用户类型
        userService.update(Wrappers.<UserEntity>lambdaUpdate()
                .set(UserEntity::getUserType, USER_TYPE_SHANG)
                .eq(UserEntity::getUserId, supplierInfo.getUserId()));

        //基本信息存入es
        //构建数据
        SupplierEsModel supplierEsModel = spuInfoService.firstEs(dto.getSupplierInfoId(), supplierInfo, null);
        //存入es
        spuInfoService.saveSupplierToSearch(supplierEsModel);


        return ResponseResult.ok();
    }

    /**
     * @param dto
     * @return com.yufubao.framework.result.ResponseResult
     * @description 用户申请商户失败
     * @author zhangyiheng
     * @date 2024/8/29 23:36
     */
    @Override
    @Transactional
    public ResponseResult merchantApplicationFila(MerchantApplicationDto dto) {
        Long supplierInfoId = dto.getSupplierInfoId();
        SupplierInfoEntity supplierInfo = supplierInfoService.getById(supplierInfoId);

        if (Objects.isNull(supplierInfo)) {
            return ResponseResult.errorResult(DATE_NOT_DATA);
        }

        SupplierApplyFailLogEntity failLog = null;

        //如果不为空之前失败过还未解决
        SupplierApplyFailLogEntity entity = supplierApplyFailLogService.getOne(Wrappers.<SupplierApplyFailLogEntity>lambdaQuery()
                .eq(SupplierApplyFailLogEntity::getLegalPerson, dto.getLegalPerson())
                .eq(SupplierApplyFailLogEntity::getStoreName, dto.getStoreName())
                .eq(SupplierApplyFailLogEntity::getIdNumber, dto.getIdNumber())
                .eq(SupplierApplyFailLogEntity::getAddress, dto.getAddress()));
        if (!Objects.isNull(entity)) {
            failLog = CopyBean.copyBean(entity, SupplierApplyFailLogEntity.class);
            failLog.setFailNumber(Optional.ofNullable(entity.getFailNumber()).orElse(0) + 1);
            failLog.setLatelyFailCause(dto.getFailCause());
            failLog.setAuditor(StpUtil.getLoginIdAsLong());
            //重置name
            Map<String, String> map = serviceUtil.getName(supplierInfo);
            failLog.setUserName(map.get("userName"));
            failLog.setCategoryName(map.get("categoryName"));
            failLog.setBeesName(map.get("beesName"));
            if (!Objects.isNull(failLog.getFailNumber()) && failLog.getFailNumber() > 1) {
                SupplierFailCauseLogEntity supplierFailCauseLogEntity = new SupplierFailCauseLogEntity();
                supplierFailCauseLogEntity.setSupplierApplyFailId(entity.getSupplierApplyFailId());
                supplierFailCauseLogEntity.setCause(dto.getFailCause());

                supplierFailCauseLogEntity.setAuditor(StpUtil.getLoginIdAsLong());

                supplierFailCauseLogService.save(supplierFailCauseLogEntity);
            }

            supplierApplyFailLogService.update(failLog, Wrappers.<SupplierApplyFailLogEntity>lambdaUpdate()
                    .eq(SupplierApplyFailLogEntity::getSupplierApplyFailId, failLog.getSupplierApplyFailId()));

        } else {
            failLog = CopyBean.copyBean(supplierInfo, SupplierApplyFailLogEntity.class);
            failLog.setLatelyFailCause(dto.getFailCause());
            failLog.setAuditor(StpUtil.getLoginIdAsLong());
            //设置name
            Map<String, String> map = serviceUtil.getName(supplierInfo);
            failLog.setUserName(map.get("userName"));
            failLog.setCategoryName(map.get("categoryName"));
            failLog.setBeesName(map.get("beesName"));
            failLog.setFailNumber(1);
            supplierApplyFailLogService.save(failLog);
        }

        supplierInfoService.removeById(supplierInfoId);
        return ResponseResult.ok();
    }


    /**
     * @param params
     * @return com.yufubao.framework.result.ResponseResult
     * @description 分页查询审核成功/待审核/审核失败的基本信息
     * @author zhangyiheng
     * @date 2024/9/15 16:16
     */
    @Override
    public ResponseResult searchAllStatusInfo(Map<String, Object> params) {

        //法人/店铺名称/手机号码
//        String key = getKey(params);
        //0待审核1审核通过2审核未通过
        String status = getStatus(params);

        PageUtils page = null;
        List<SearchAllStatusInfoVo> vos = new ArrayList<>();
        if (StrUtil.isNotBlank(status)) {
            switch (status) {
                case WAIT:
                case SUCCESS:
                    //待审核、审核成功
                    page = supplierInfoService.searchAllStatusInfo(params);
                    List<SupplierInfoEntity> list = (List<SupplierInfoEntity>) page.getList();
                    if (MyCollUtil.isNotEmpty(list)) {
                        for (SupplierInfoEntity po : list) {
                            SearchAllStatusInfoVo vo = CopyBean.copyBean(po, SearchAllStatusInfoVo.class);
                            //设置用户名和主营分类名/小蜜蜂名
                            Map<String, String> map = serviceUtil.getName(po);
                            vo.setUserName(map.get("userName"));
                            vo.setCategoryName(map.get("categoryName"));
                            vo.setBeesName(map.get("beesName"));

                            vos.add(vo);
                        }
                        page.setList(vos);
                        return ResponseResult.okResultPage("page", page);
                    }
                    break;
                case FAIL:
                    //审核失败
                    page = supplierApplyFailLogService.searchAllStatusInfo(params);
                    List<SupplierApplyFailLogEntity> list2 = (List<SupplierApplyFailLogEntity>) page.getList();
                    if (MyCollUtil.isNotEmpty(list2)) {
                        vos = CopyBean.copyBeanList(list2, SearchAllStatusInfoVo.class);
                        vos.forEach(po->po.setStatus(FAIL));
                        page.setList(vos);
                        return ResponseResult.okResultPage("page", page);
                    }
                    break;
                default:
                    break;
            }
        }
        return ResponseResult.okResultPage("page", page);
    }

    /**
     * @param supplierInfoId
     * @return com.yufubao.framework.result.ResponseResult
     * @description 根据id查询, 待审核
     * @author zhangyiheng
     * @date 2024/9/17 22:31
     */
    @Override
    public ResponseResult searchWaitPass(Long supplierInfoId) {

        SearchAllStatusInfoVo vo = supplierInfoService.searchWaitPass(supplierInfoId);
        if (Objects.isNull(vo)) {
            throw new BaseException(NOT_FOUND_HYBSH);
        }
        return ResponseResult.okResult(vo);
    }
}
